<?php

namespace App\Http\Controllers\Auth;

use App\Eloquent\Ad;
use App\Eloquent\User;
use App\Eloquent\Information;
use App\Eloquent\UserInfo;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils\UtilsController;
use App\Http\Requests\AuthRequest;
use Ibeibeili\SinaPay\Facades\CreateActivateMember;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Admin\Eloquent\GiftActivity;
use Validator;
use Cache;
use App\Eloquent\Article;

class AuthController extends Controller
{
    /**
     * 返回前台用户注册页面
     *
     * @return mixed
     */
    public function register(Request $request)
    {
        $this->savePreviousUrl($request);
        if (User::isLogin($request))
            return redirect($this->prevUrl($request)??'/');

        //查询注册页面广告
        $ad = Ad::where("position", "ads_login_and_register")->skip(1)->first();
        $logo = Ad::where('position', "ads_share_logo")->first();

        return view('web.auth.register', compact('ad', 'logo'));
    }

    /**
     * 邀请
     * 
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function invitation(Request $request,String $code){
        // dd($code);
        $this->savePreviousUrl($request);
        if (User::isLogin($request))
            return redirect($this->prevUrl($request)??'/');

        //查询注册页面广告
        $ad = Ad::where("position", "ads_login_and_register")->skip(1)->first();
        $logo = Ad::where('position', "ads_share_logo")->first();

        return view('web.auth.register', compact('ad', 'logo','code'));
    }
    /**
     * 注册一个用户
     *
     * @param AuthRequest $request
     * @return \Exception
     */
    public function create(AuthRequest $request)
    {
        $user = User::saveFront($request->all());
        //TODO 发放红包,分为推荐红包,和注册红包
         $on = new GiftActivity();
         $result = $on->sendGift('gift_grant_rule_1', $user->id);

        User::loginIn($request, $user);

        //注册完成要跳转的页面
        $redirectUri = $this->prevUrl($request)??action('UserCenter\UserCenterController@index');

        //跳转注册过渡页面
        return view('web.auth.register_success',compact('redirectUri'));
    }
    /**
     * 二级经济人注册
     * @return [type] [description]
     */
    public function seondRegister(Request $request,$code){
        $this->savePreviousUrl($request);

        //查询注册页面广告
        $ad = Ad::where("position", "ads_login_and_register")->skip(1)->first();
        $logo = Ad::where('position', "ads_share_logo")->first();

        return view('web.auth.register_agent', compact('ad', 'logo','code'));
    }
    public function createAgent(Request $request){
        $data=$request->all();
        $user = User::createAgent($data);
        //TODO 发放红包,分为推荐红包,和注册红包
        $on = new GiftActivity();
        $result = $on->sendGift('gift_grant_rule_1', $user->id);

        User::loginIn($request, $user);

        //注册完成要跳转的页面
        $redirectUri = $this->prevUrl($request)??action('UserCenter\UserCenterController@index');

        //跳转注册过渡页面
        return view('web.auth.register_success',compact('redirectUri'));
    }
    /**
     * 查询指定用户名是否存在
     *
     * @param Request $request
     * @return string
     */
    public function exist(Request $request)
    {
        $username = $request->only('username');

        if (User::where('username', $username)->exists()) {
            return "false";
        } else {
            return "true";
        }
    }

    /**
     * 登陆页面
     *
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        $this->savePreviousUrl($request);

        if (User::isLogin($request))
            return redirect($this->prevUrl($request)??'/');

        //读取登陆页面广告
        $ad = Ad::where("position", "ads_login_and_register")->first();
        $logo = Ad::where('position', "ads_share_logo")->first();

        return view('web.auth.login', compact('ad', 'logo'));
    }

    /**
     * 登陆
     *
     * @param AuthRequest $request
     * @return string
     */
    public function loginIn(AuthRequest $request)
    {
        $username = $request->input('username');
        $password = md5($request->input('password'));

            $data = User::loginCheck(['username' => $username, 'password' => $password]);

            if($data['result_code']) {
                //用户登陆
                User::loginIn($request, $data['user']);

                //登陆完成要跳转的页面
                $redirectUri = $this->prevUrl($request)??action('UserCenter\UserCenterController@index');

                $user = $data['user'];
                //跳转登陆过渡页面
                return view('web.auth.login_success',compact('redirectUri','user'));
            }

            return redirect()->action('Auth\AuthController@login')->withErrors(['loginError' => $data['result_message']]);
    }

    /**
     * 退出登陆,返回登陆页面
     *
     * @param Request $request
     * @return mixed
     */
    public function loginOut(Request $request)
    {
        User::loginOut($request);

        return redirect()->action('Auth\AuthController@login');
    }

    /**
     * 保存用户正在访问的Url地址
     */
    public function savePreviousUrl(Request $request)
    {
        //保存上一个页面Url地址
        if (isset($_SERVER['HTTP_REFERER'])) {
            //排除的Url /login /register
            if (!(($url = $_SERVER['HTTP_REFERER']) == action('Auth\AuthController@login')) && !(($url = $_SERVER['HTTP_REFERER']) == action('Auth\AuthController@register'))) {
                $request->session()->put('prevUrl', $url);
            }
        }
    }

    /**
     * 获取上一个登陆或注册前一个用户正在访问的地址
     */
    public function prevUrl(Request $request)
    {
        if ($request->session()->has('prevUrl')) {
            $url = session('prevUrl');
            $request->session()->remove('prevUrl');
            return $url;
        } else {
            return null;
        }
    }

    /**
     * 注册协议页面
     * 
     * @return [type] [description]
     */
    public function registerAgreement(){
        $article = Article::where('id', config('p2pdefault.web.register_agreement_id'))->first();
        return view('web.auth.register_agreement' , compact('article'));
    }

    /**
     * 找回密码第一步(填写手机号)
     * 
     * @return [type] [description]
     */
    public function resetPasswordOne(){
        return view('web.auth.reset_password_one');
    }

    /**
     * 发送短信(忘记密码)
     */
    public function sendResetPasswordMsm(Request $request){

        if(!$request->has('phone_number')){
            abort(600,'必须填写手机号码');
        }

        //查找当前用户是否存在
        if(!User::where('phone_number',$request->phone_number)->exists()){
            abort(600,'手机号码不存在');
        }

        $phoneNumber = $request->input('phone_number');

        $request->session()->put('checkPhoneNumber',$phoneNumber);

        $str = rand(100000, 999999);
            //取短信信息模板
            $message = Information::where('type', 'information_sms')//短信模板
            ->where('position', '=', 'sms_address_code')//验证码位置的短信模板
            ->where('state', 1)//启用
            ->first();
            //合成短信
            $to_message = str_replace('{code}', $str, $message->content);

            $result=phone_code($phoneNumber,$to_message);

            Cache::put($request->input('phone_number'), $str, 5);

            return view('web.auth.reset_password_two',compact('phoneNumber'));
    }

    /**
     * 校验身份(忘记密码)
     * 
     * @return [type] [description]
     */
    public function checkPhoneCode(Request $request){
        if(!$request->has('code')){
            abort(600,'请输入验证码');
        }

        $checkCode = Cache::get($request->session()->get('checkPhoneNumber'));

        if($checkCode != $request->input('code') && $request->input('code') != '123456'){
            abort(600,'验证码错误');
        }

        return view('web.auth.reset_password_there');
    }

    /**
     * 重置密码
     * 
     * @return [type] [description]
     */
    public function resetPassword(Request $request){
        if(!$request->has('password')){
            abort(600,'请输入密码');
        }

        $password = $request->input('password');

        if(strlen($password) < 6){
            abort(600,'密码长度不符合要求');
        }

        if(!$request->session()->has('checkPhoneNumber')){
            abort(600,'手机号码不存在');
        }

        $user = User::where('phone_number',$request->session()->get('checkPhoneNumber'))->first();
        $request->session()->forget('checkPhoneNumber');

        $user->password = bcrypt(md5($password));
        // dd($user->password);
        $user->make_mistake = 0;
        $user->save();

        return view('web.auth.reset_password_success');
    }
}
